package com.bookstore.spring.util;


import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Map;


/**
 * Created by Admin on 2016/8/15.
 */
public class FormUtils {

    @SuppressWarnings("all")
    public static Object parseForm(HttpServletRequest request, Class clazz, String enc) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, UnsupportedEncodingException {
        request.setCharacterEncoding(enc);
        String methodName=request.getMethod();
        String queryString = request.getQueryString();

        Map<String, String[]> map = request.getParameterMap();
        Object obj = clazz.newInstance();
        for (String key : map.keySet()) {
            //根据key 获取字段
            try {
                Field field = clazz.getDeclaredField(key);
                String typeSimpleName = field.getType().getSimpleName();
                if ("Integer,int".contains(typeSimpleName)) {
                    Method method = clazz.getMethod("set" + key.substring(0, 1).toUpperCase() + key.substring(1), field.getType());
                    method.invoke(obj, Integer.valueOf(map.get(key)[0]));
                } else if ("Long,long".contains(typeSimpleName)) {
                    Method method = clazz.getMethod("set" + key.substring(0, 1).toUpperCase() + key.substring(1), field.getType());
                    method.invoke(obj, Long.valueOf(map.get(key)[0]));
                } else if ("double,Double".contains(typeSimpleName)) {
                    Method method = clazz.getMethod("set" + key.substring(0, 1).toUpperCase() + key.substring(1), field.getType());
                    method.invoke(obj, Double.valueOf(map.get(key)[0]));
                } else if ("Date".contains(typeSimpleName)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Method method = clazz.getMethod("set" + key.substring(0, 1).toUpperCase() + key.substring(1), field.getType());
                    method.invoke(obj, sdf.parse(map.get(key)[0]));
                } else {
                    Method method = clazz.getMethod("set" + key.substring(0, 1).toUpperCase() + key.substring(1), field.getType());
                    method.invoke(obj, map.get(key));
                }
            } catch (Exception e) {
                System.err.println(e.getMessage());
            }
        }
        return obj;
    }
}
